package com.sunday.aomicaichang.adpter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.widgets.MarqueeView;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.ui.MainActivity;
import com.sunday.aomicaichang.ui.MallActivity;
import com.sunday.aomicaichang.ui.MenuActivity;
import com.sunday.aomicaichang.ui.MenuDetailActivity;
import com.sunday.aomicaichang.ui.SignActivity;
import com.sunday.aomicaichang.ui.common.WebViewActivity;
import com.sunday.aomicaichang.ui.product.ProductActivity;
import com.sunday.aomicaichang.ui.product.SearchProductListActivity;
import com.sunday.member.entity.CookBooks;
import com.sunday.member.entity.news.News;
import com.sunday.member.entity.product.Product;
import com.sunday.member.entity.product.ProductCategory;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class IndexAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private final static int TYPE_HEAD = 0;
    private final static int TYPE_LIST = 1;
    private List<Product> productList;
    private List<ProductCategory> categoryList;
    private List<News> imageList;
    private List<CookBooks> cookBooksList;
    private List<News> newsList;


    public IndexAdapter(Context context) {
        mContext = context;
    }

    public IndexAdapter(Context context, List<News> imgList, List<News>newsList, List<CookBooks> cookBookses,List<Product> products, List<ProductCategory> categories) {
        mContext = context;
        this.productList = products;
        this.categoryList = categories;
        this.cookBooksList=cookBookses;
        this.imageList=imgList;
        this.newsList=newsList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_HEAD:
                View view = LayoutInflater.from(mContext).inflate(R.layout.layout_index_head, null);
                return new HeadHolder(view);
            case TYPE_LIST:
                view = LayoutInflater.from(mContext).inflate(R.layout.layout_index_list, null);
                return new ListHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case TYPE_HEAD:
                HeadHolder headHolder = (HeadHolder) holder;
                headHolder.dataSet.clear();
                headHolder.dataSet.addAll(categoryList);
                headHolder.adapter.notifyDataSetChanged();
                headHolder.dataSet1.clear();
                headHolder.dataSet1.addAll(cookBooksList);
                headHolder.adapter1.notifyDataSetChanged();
                headHolder.banner.setPages(headHolder.viewHolderCreator,imageList)
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                        .setPageIndicator(new int[]{R.mipmap.ic_page_indicator,R.mipmap.ic_page_indicator_focused});
                headHolder.banner.notifyDataSetChanged();
                //文字公告
                List<String> notices = new ArrayList<>();
                for (int i=0;i<newsList.size();i++){
                    notices.add(newsList.get(i).getName());
                }
                headHolder.marqueeView.startWithList(notices);
                headHolder.marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, TextView textView) {

                        Intent intent=new Intent(mContext, WebViewActivity.class);
//                        intent.putExtra("title","资讯详情");
//                        long memberId = BaseApp.getInstance().getMember().getId();
//                        intent.putExtra("url",newsList.get(position).getUrl()+"&memberId="+memberId);
//                        mContext.startActivity(intent);
                        switch (newsList.get(position).getPageType()) {
                            case 0://打开url
                                intent = new Intent(mContext, WebViewActivity.class);
                                intent.putExtra("title", "资讯详情");
                                long memberId = BaseApp.getInstance().getMember().getId();
                               // intent.putExtra("url",newsList.get(position).getUrl()+"&memberId="+memberId);
                                intent.putExtra("url",newsList.get(position).getUrl());
                                break;
                            case 1://打开商品详情
                                intent = new Intent(mContext, ProductActivity.class);
                                intent.putExtra("id", Long.valueOf(newsList.get(position).getPageId()));
                                intent.putExtra("name",newsList.get(position).getName());
                                break;
                            case 2://打开商品列表
                                intent = new Intent(mContext, SearchProductListActivity.class);
                                intent.putExtra("catId", newsList.get(position).getPageId());
                                break;
                            case 3://打开商户详情
                                break;
                        }
                        mContext.startActivity(intent);
                    }
                });
                break;
            case TYPE_LIST:
                ListHolder listHolder= (ListHolder) holder;
                Product item=productList.get(position-1);
                if (!TextUtils.isEmpty(item.getImage())){
                    Picasso.with(mContext)
                            .load(item.getImage())
                            .error(R.mipmap.ic_product)
                            .resize(150,150).into(listHolder.productImg);
                }
                listHolder.productTitle.setText(item.getName());
                listHolder.priceNow.setText(SpannalbeStringUtils.setTextSizePx("零售价：￥", PixUtils.sp2px(mContext,12)));
                listHolder.priceNow.append(SpannalbeStringUtils.setTextSizePx(
                        String.valueOf(item.getPrice().setScale(2, RoundingMode.HALF_UP)),PixUtils.sp2px(mContext,15)));
                listHolder.priceOld.setText(String.format("￥%s",item.getMarketPrice().setScale(2,RoundingMode.HALF_UP)));
                listHolder.priceOld.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG|Paint.STRIKE_THRU_TEXT_FLAG);
                listHolder.totalLayout.setTag(item);
                break;
        }
    }

    @Override
    public int getItemCount() {
        return productList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_HEAD;
        } else {
            return TYPE_LIST;
        }
    }

    class HeadHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.banner)
        ConvenientBanner banner;
        @Bind(R.id.marquee_view)
        MarqueeView marqueeView;
        @Bind(R.id.category_recylerview)
        RecyclerView recyclerView;
        @Bind(R.id.recycler_view)
        RecyclerView recyclerView1;
        @Bind(R.id.text2)
        TextView text2;
        @Bind(R.id.header_layout)
        LinearLayout headerLayout;
        @Bind(R.id.ly_cook_books)
        RelativeLayout lyCookBooks;
        private LinearLayoutManager layoutManager,layoutManager1;
        private CommonAdapter<ProductCategory> adapter;
        private List<ProductCategory> dataSet = new ArrayList<>();
        private CommonAdapter<CookBooks> adapter1;
        private List<CookBooks> dataSet1 = new ArrayList<>();
        private NewsBannerHolder bannerViewHolder;
        private ViewHolderCreator viewHolderCreator;

        public HeadHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            layoutManager = new LinearLayoutManager(mContext);
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            recyclerView.setLayoutManager(layoutManager);
            adapter = new CommonAdapter<ProductCategory>(mContext, R.layout.item_mine_menu_item, dataSet) {
                @Override
                public void convert(RecylerViewHolder holder, ProductCategory productCategory) {
                    bind(holder, productCategory);
                }
            };
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            layoutManager1 = new LinearLayoutManager(mContext);
            layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
            recyclerView1.setLayoutManager(layoutManager1);
            adapter1 = new CommonAdapter<CookBooks>(mContext, R.layout.item_main_cookbooks, dataSet1) {
                @Override
                public void convert(RecylerViewHolder holder, CookBooks cookBooks) {
                    bind1(holder, cookBooks);
                }
            };
            recyclerView1.setAdapter(adapter1);
            adapter1.notifyDataSetChanged();
            banner.startTurning(3000);
            bannerViewHolder = new NewsBannerHolder();
            viewHolderCreator = new ViewHolderCreator<NewsBannerHolder>() {

                @Override
                public NewsBannerHolder createHolder() {
                    return bannerViewHolder;
                }
            };
            lyCookBooks.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(mContext,MenuActivity.class);
                    mContext.startActivity(intent);
                }
            });
            bannerViewHolder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            banner.startTurning(3000);
            bannerViewHolder = new NewsBannerHolder();
            viewHolderCreator = new ViewHolderCreator<NewsBannerHolder>() {

                @Override
                public NewsBannerHolder createHolder() {
                    return bannerViewHolder;
                }
            };
            bannerViewHolder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News item = (News) v.getTag();
                    Intent intent = null;
                    switch (item.getPageType()) {
                        case 0://打开url
                            intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra("title", "资讯详情");
                            long memberId = BaseApp.getInstance().getMember().getId();
                            //intent.putExtra("url",item.getUrl()+"&memberId="+memberId);
                            intent.putExtra("url",item.getUrl());
                            break;
                        case 1://打开商品详情
                            intent = new Intent(mContext, ProductActivity.class);
                            intent.putExtra("id", Long.valueOf(item.getPageId()));
                            intent.putExtra("name",item.getName());
                            break;
                        case 2://打开商品列表
                            intent = new Intent(mContext, SearchProductListActivity.class);
                            intent.putExtra("catId", item.getPageId());
                            break;
                        case 3://打开商户详情
                            break;
                    }
                    mContext.startActivity(intent);
                }
            });
        }
    }

    private void bind(RecylerViewHolder holder, final ProductCategory productCategory) {
        LinearLayout linearLayout = holder.getView(R.id.service_item);
        RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(DeviceUtils.getDisplay(mContext).widthPixels * 2 / 10, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(params);
        ImageView imgView = holder.getView(R.id.item_image);
        if("1".equals(productCategory.getImage())){
            imgView.setImageResource(R.mipmap.main_sign);
        }else if("2".equals(productCategory.getImage())){
            imgView.setImageResource(R.mipmap.main_menu_book);
        }else if("3".equals(productCategory.getImage())){
            imgView.setImageResource(R.mipmap.main_mall);
        }else if (!TextUtils.isEmpty(productCategory.getImage())&&!"1".equals(productCategory.getImage())
                &&!"2".equals(productCategory.getImage())
                &&!"3".equals(productCategory.getImage())) {
            Picasso.with(mContext)
                    .load(productCategory.getImage())
                    .error(R.mipmap.ic_product)
                    .resize(150, 150)
                    .into(imgView);
        }
        ((TextView) (holder.getView(R.id.item_text))).setText(productCategory.getName());
        holder.setOnClickListener(R.id.service_item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("1".equals(productCategory.getImage())){
                    Intent intent = new Intent(mContext, SignActivity.class);
                    mContext.startActivity(intent);
                }else if("2".equals(productCategory.getImage())){
                    Intent intent = new Intent(mContext, MenuActivity.class);
                    mContext.startActivity(intent);
                }else if("3".equals(productCategory.getImage())){
                    Intent intent = new Intent(mContext, MallActivity.class);
                    mContext.startActivity(intent);
                }else {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra("parentId", productCategory.getId());
                    intent.putExtra("pageNo", 1);
                    mContext.startActivity(intent);
                }
            }
        });

    }
    private void bind1(RecylerViewHolder holder, final CookBooks cookBooks) {
        LinearLayout linearLayout = holder.getView(R.id.item);
        RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(DeviceUtils.getDisplay(mContext).widthPixels / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(params);
        ImageView imgView = holder.getView(R.id.img);
        if (!TextUtils.isEmpty(cookBooks.getImage())) {
            Picasso.with(mContext)
                    .load(cookBooks.getImage())
                    .error(R.mipmap.ic_product)
                    .resize(150, 150)
                    .into(imgView);
        }
        if(cookBooks.getName()!=null)
        ((TextView) (holder.getView(R.id.name))).setText(cookBooks.getName());
        if(cookBooks.getViceName()!=null)
        ((TextView) (holder.getView(R.id.sub))).setText(cookBooks.getViceName());
        holder.setOnClickListener(R.id.item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent intent=new Intent(mContext, MenuDetailActivity.class);
                    intent.putExtra("id",cookBooks.getId());
                    mContext.startActivity(intent);
            }
        });

    }
    class ListHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @Bind(R.id.product_img)
        ImageView productImg;
        @Bind(R.id.product_title)
        TextView productTitle;
        @Bind(R.id.price_now)
        TextView priceNow;
        @Bind(R.id.price_old)
        TextView priceOld;
        @Bind(R.id.btn_buy)
        TextView btnBuy;
        @Bind(R.id.total_layout)
        RelativeLayout totalLayout;

        public ListHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            totalLayout.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Product item= (Product) v.getTag();
            Intent intent=new Intent(mContext, ProductActivity.class);
            intent.putExtra("id",item.getId());
            intent.putExtra("name",item.getName());
            mContext.startActivity(intent);
        }
    }

}
